package com.hxgis.oc.util.netcdf;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import ucar.ma2.ArrayFloat;
import ucar.ma2.DataType;
import ucar.nc2.NetcdfFile;
import ucar.nc2.NetcdfFiles;
import ucar.nc2.Variable;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Getter
public class NetcdfBuffer {
    private int width;
    private int height;
    List<byte[]> varBufferList = new ArrayList<>();
    List<float[]> floatBufferList = new ArrayList<>();

    public boolean read(String fileName,String[] varName){
        NetcdfFile dataset = null;
        try{
            dataset = NetcdfFiles.open(fileName);

            int[] shape = null;
            int[] origin = null;

            for(String var : varName)
            {
                Variable var1 = dataset.findVariable(var);
                assert var1 != null;
                if(shape == null){
                    shape = var1.getShape();
                    origin = new int[shape.length];
                    height = shape[shape.length - 2];
                    width = shape[shape.length - 1];
                }
                ArrayFloat.D2 varBuffer1 = (ArrayFloat.D2)(var1.read(origin, shape).reduce());
                varBufferList.add(varBuffer1.getDataAsByteBuffer().array());
                floatBufferList.add((float[]) varBuffer1.get1DJavaArray(DataType.FLOAT));
            }
        }
        catch(Exception e) {
            log.error(e.getMessage());
        }
        finally {
            if(dataset != null){
                try {
                    dataset.close();
                    new File(fileName + ".gbx9").delete();
                    new File(fileName + ".ncx4").delete();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return !varBufferList.isEmpty();
    }
}
